package ctm.javacode;

import java.io.* ;
import java.util.*;
import java.sql.*;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/register.do")

public class register extends HttpServlet {

	private final String SUCCESS_VIEW = "main.jsp";  
	private final String ERROR_VIEW = "registerError.jsp"; 
	
	protected void doPost(HttpServletRequest request,
								HttpServletResponse response )
								throws ServletException, IOException {
		String nextpage = ERROR_VIEW;
		
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		
		String ac = request.getParameter("newaccount") ;
		String pw = request.getParameter("newpw") ;
		String repw = request.getParameter("renewpw") ;
		String mail = request.getParameter("email") ;
		String role = request.getParameter("role");
		String sex = request.getParameter("sex");
		String name = request.getParameter("username") ;
		String education = request.getParameter("education");
		String marriage = request.getParameter("marriage");
		String job = request.getParameter("job");
		String liveWith = request.getParameter("liveWith");
		String year = request.getParameter("year");
		String height = request.getParameter("height") ;
		String weight = request.getParameter("weight") ;
		
		List<String> errors = new ArrayList<String>() ;
		
		try {
			if (isInvalidAccount( ac ))
				errors.add("帳號不符合規定或者帳號已經存在");
		} catch (NamingException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}		
		if (isInvalidPW( pw ))
			errors.add("密碼格式不正確");
		if ( ! pw.equals(repw))
			errors.add("密碼不一致");
		if(isInvalidUsername(name))
			errors.add("使用者名稱格式不正確");
		if (isInvalidMail( mail ))
			errors.add("E-mail格式不正確,請您注意必須使用小寫");
		
	
		
		if ( errors.isEmpty() ) {
			nextpage = SUCCESS_VIEW ;
			try {
				creatUserData(ac, pw, name,sex,mail, role, education, marriage, job, liveWith, year, height, weight);
			} catch (NamingException e) {
				errors.add("資料庫出錯誤");
				request.setAttribute("errors", errors) ;
				nextpage = ERROR_VIEW ;
				e.printStackTrace();
			} catch (SQLException e) {
				errors.add("資料庫出錯誤");
				request.setAttribute("errors", errors) ;
				nextpage = ERROR_VIEW ;
				e.printStackTrace();
			}
		} // end if
		else {
			request.setAttribute("errors", errors) ;
		} // end else
			
	
		request.getRequestDispatcher(nextpage)
		   .forward(request, response);
	} // end doPost()

	private void creatUserData(String ac, String pw, String name,String sex,String mail, String role, String education, String marriage, String job, String liveWith, String year, String height, String weight) throws NamingException, SQLException {
		dbBean creatData = new dbBean("jdbc/ctmpllab");
		pw = md5Encrypt.generate(pw);//用md5加密帳戶密碼
		
		String sqlQuery = "INSERT INTO accounttable(account, password, role, email,name,sex, education , marriage , job , liveWith , year , height , weight) VALUES('"
					+ ac + "', '" + pw + "', '" + role + "', '" + mail + "','"+ name + "','"+ sex  + "','" + education + "','" + marriage + "','" + job + "','" + liveWith + "','" +  year+ "','" + height + "','" +  weight +"')" ;	
		

		creatData.Connected();
		try {
			creatData.ExcuteUpdate(sqlQuery);		    
		} catch(SQLException e) {
			throw new SQLException(e) ;
		} // end try-catch				

	}

	private boolean isInvalidMail(String mail) {
		return mail == null || ! mail.matches("^[_a-zA-Z0-9]+([.]" + "[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+([.][a-zA-Z0-9-]+)*$");
		
	}

	private boolean isInvalidPW(String pw) {
		return pw== null || pw.length() < 6 || pw.length() > 12 ;
	
	}
	private boolean isInvalidUsername(String name){
		return name == "";
	}

	private boolean isInvalidAccount(String ac) throws NamingException, SQLException {
		dbBean db = new dbBean("jdbc/ctmpllab");
		ResultSet rs ;
		
		db.Connected();
		try {
			rs = db.ExcuteQuery("SELECT * FROM accounttable");		    
		} catch(SQLException e) {
			throw new SQLException(e) ;
		} // end try-catch
			
		while (rs.next()) {
			if ( rs.getString("account").trim().equals(ac) )
				return true;
		} // end while
			
		if ( ac.length() < 6 || ac.length() > 12 )
			return true;

			
		return false ;
	}
	
} // end class register

